package com.jcl.recruit.api.apply.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jcl.recruit.apply.model.Interview;
import com.jcl.recruit.apply.model.InterviewSkd;
import com.jcl.recruit.apply.service.InterviewService;
import com.jcl.recruit.apply.service.InterviewSkdService;
import com.jcl.recruit.common.service.CommonService;
import com.jcl.recruit.core.config.SpringConfig;
import com.jcl.recruit.org.service.DepartmentService;
import com.jcl.recruit.resume.model.Resume;
import com.jcl.recruit.resume.service.ResumeBaseService;
import com.jcl.recruit.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.springframework.beans.support.PagedListHolder.DEFAULT_PAGE_SIZE;

/**
 * @author 刘明新
 * @date 2018/8/6 下午1:55
 */
@RestController
@RequestMapping("/api")
public class InterviewController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private UserService userService;

    @Autowired
    private InterviewSkdService interviewSkdService;

    @Autowired
    private InterviewService interviewService;

    @Autowired
    private ResumeBaseService resumeService;

    @Autowired
    private SpringConfig springConfig;

    /**
     * 新增面试安排
     * @param entity
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    @RequestMapping(value = "/interviewskd/save",method = RequestMethod.POST)
    public Map<String,Object> interviewskdSave(@RequestBody Map<String,String> entity){
        Map<String,Object> map = new LinkedHashMap<>();
        if(StringUtils.isBlank(entity.get("department_id")) || StringUtils.isBlank(entity.get("hr_id")) ||
                StringUtils.isBlank(entity.get("manager_id")) || StringUtils.isBlank(entity.get("schedule"))){
            map.put("type","error");
            map.put("message","执行失败");
            map.put("errors","[]");
            return map;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Interview interview = interviewService.selectCountByResumeId(Integer.valueOf(entity.get("resume_id")));
        Date date = sdf.parse(entity.get("schedule"),new ParsePosition(0));
        if(interview == null){
            interview = new Interview();
            interview.setResumeId(Integer.valueOf(entity.get("resume_id")));
            interview.setJob(entity.get("job"));
            interview.setCreatetime(new Date());
            interview.setLastSkdDepartmentId(Integer.valueOf(entity.get("department_id")));
            interview.setLastSkdDepartment(departmentService.selectPrimarykeyById(interview.getLastSkdDepartmentId()).getShortname());
            interview.setLastSkdHrId(Integer.valueOf(entity.get("hr_id")));
            interview.setLastSkdHr(userService.selectPrimaryKeyById(interview.getLastSkdHrId()).get("realname").toString());
            interview.setLastSkdManagerId(Integer.valueOf(entity.get("manager_id")));
            interview.setLastSkdHr(userService.selectPrimaryKeyById(interview.getLastSkdManagerId()).get("realname").toString());
            interview.setLastSkdTime(interview.getCreatetime());
            interview.setStep(0);
            interview.setSkdnums(0);
            interview.setStatus(0);
            interview.setLastSkdPlace(entity.get("schedule_place"));
            interviewService.insertSelective(interview);
            Resume resume = new Resume();
            resume.setUpdatetime(new Date());
            resume.setStatus(2);
            resume.setId(interview.getResumeId());
            resumeService.updateByPrimaryKeySelective(resume);
        }
        if(interviewSkdService.selectCountByScheduleOptions(date,interview.getId(),Integer.valueOf(entity.get("hr_id"))) > 0){
            map.put("type","error");
            map.put("message","执行失败");
            map.put("errors","该HR已经在相同时间安排过相同的人面试");
            return map;
        }
        /*if(interviewService.selectCountByResumeId(Integer.valueOf(entity.get("resume_id"))) > 0){
            map.put("type","error");
            map.put("message","执行失败");
            map.put("errors","该简历已经安排过其他面试");
            return map;
        }*/
        InterviewSkd interviewSkd = new InterviewSkd();
        interviewSkd.setId(StringUtils.isNotBlank(entity.get("id"))?Integer.valueOf(entity.get("id")):null);
        interviewSkd.setCreatetime(new Date());
        interviewSkd.setDepartmentId(Integer.valueOf(entity.get("department_id")));
        interviewSkd.setDepartment(departmentService.selectPrimarykeyById(interviewSkd.getDepartmentId()).getShortname());
        interviewSkd.setHrId(Integer.valueOf(entity.get("hr_id")));
        interviewSkd.setHr(userService.selectPrimaryKeyById(interviewSkd.getHrId()).get("realname").toString());
        interviewSkd.setManagerId(Integer.valueOf(entity.get("manager_id")));
        interviewSkd.setManager(userService.selectPrimaryKeyById(interviewSkd.getManagerId()).get("realname").toString());
        interviewSkd.setResult(entity.get("result"));
        interviewSkd.setScheduleTime(entity.get("schedule").substring(11));
        interviewSkd.setScheduleDate(sdf.parse(entity.get("schedule"),new ParsePosition(0)));
        interviewSkd.setSchedulePlace(entity.get("schedule_place"));
        interviewSkd.setInterviewId(interview.getId());
        interviewSkdService.insertOrUpdate(interviewSkd);
        //测试环境不执行此代码
        if(!springConfig.getSpringProfiles().equals("idc")) {
            CommonService.synResume thread = new CommonService().new synResume(interviewSkdService.selectAllInterviewSkdsByInterviewId(interview.getId()),
                    userService.selectPrimaryKeyByToken(entity.get("token")).get("id").toString(), resumeService.selectPrimarykeyByEntity(interview.getResumeId()));
            System.out.println("开始异步请求");
            thread.run();
        }
        map.put("type","success");
        map.put("message","执行成功");
        map.put("interviewskd",interviewSkdService.selectPrimaryKeyById(interviewSkd.getId()));
        return map;
    }

    /**
     * 修改面试结果
     * @param entity
     * @return
     */
    @RequestMapping(value = "/interviewskd/modify",method = RequestMethod.POST)
    public Map<String,Object> interviewskdModify(@RequestBody Map<String,String> entity){
        Map<String,Object> map = new HashMap<>();
        if(entity.get("id") == null){
            map.put("type","error");
            map.put("message","执行失败");
            map.put("errors","[]");
            return map;
        }
        InterviewSkd interviewSkd = new InterviewSkd();
        interviewSkd.setId(Integer.valueOf(entity.get("id")));
        interviewSkd.setStatus(Integer.valueOf(entity.get("status")));
        interviewSkd.setResult(entity.get("result"));
        interviewSkdService.insertOrUpdate(interviewSkd);
        Map<String,Object> interviewSKdMap = interviewSkdService.selectPrimaryKeyById(interviewSkd.getId());
        if(!springConfig.getSpringProfiles().equals("idc")) {
            Map<String,Object> interview = interviewService.selectPrimaryKeyById((Integer)interviewSKdMap.get("interview_id"));
            CommonService.synResume thread = new CommonService().new synResume(interviewSkdService.selectAllInterviewSkdsByInterviewId((Integer)interview.get("id")),
                    userService.selectPrimaryKeyByToken(entity.get("token")).get("id").toString(), resumeService.selectPrimarykeyByEntity((Integer)interview.get("resume_id")));
            System.out.println("开始异步请求");
            thread.run();
        }
        map.put("type","success");
        map.put("message","执行成功");
        map.put("interviewskd",interviewSKdMap);
        return map;
    }

    /**
     * 面试安排记录
     * @param schedule_date_start
     * @param schedule_date_end
     * @return
     * @throws ParseException
     */
    @RequestMapping("/interviewskd/find")
    public Map<String,Object> interviewskdFind(String schedule_date_start,String schedule_date_end,String token,Integer interview_id,
                                               @RequestParam(value = "page", required = false, defaultValue = "1") String toPage){
        Map<String,Object> map = new LinkedHashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat();
        Date startDate = null;
        if(StringUtils.isNotBlank(schedule_date_start)){
            startDate = sdf.parse(schedule_date_start,new ParsePosition(0));
        }
        Date endDate = null;
        if(StringUtils.isNotBlank(schedule_date_end)){
            endDate = sdf.parse(schedule_date_end,new ParsePosition(0));
        }
        PageHelper.startPage(Integer.valueOf(toPage),DEFAULT_PAGE_SIZE);
        List<Map<String,Object>> interviewSkdList = interviewSkdService.selectInterviewSkdsByDate(startDate,endDate,token,interview_id);
        PageInfo pageInfo = new PageInfo(interviewSkdList);
        map.put("type","success");
        map.put("message","执行成功");
        map.put("interviewskds",pageInfo.getList());
        map.put("total",pageInfo.getTotal());
        return map;
    }

    /**
     * 面试安排记录。单个
     * @param id
     * @return
     */
    @RequestMapping("/interviewskd/get/{id}")
    public Map<String,Object> interviewskdGet(@PathVariable("id")Integer id){
        Map<String,Object> map = new LinkedHashMap<>();
        map.put("type","success");
        map.put("message","成功");
        map.put("interviewskd",interviewSkdService.selectPrimaryKeyById(id));
        return map;
    }

    /**
     * 面试列表
     * @return
     */
    @RequestMapping("/interview/find")
    public Map<String,Object> interviewFind(@RequestParam(value = "page", required = false, defaultValue = "1") String toPage, Integer status){
        Map<String,Object> map = new LinkedHashMap<>();
        PageHelper.startPage(Integer.valueOf(toPage),DEFAULT_PAGE_SIZE);
        List<Map<String,Object>> list = interviewService.selectAllInterviews(status);
        PageInfo pageInfo = new PageInfo(list);
        map.put("type","success");
        map.put("message","获取成功");
        map.put("interviews",pageInfo.getList());
        map.put("total",pageInfo.getTotal());
        map.put("cnt",interviewService.selectCountByStatus());
        return map;
    }

    /**
     * 获取单个面试记录
     * @param id
     * @return
     */
    @RequestMapping("/interview/get/{id}")
    public Map<String,Object> interviewGetDetail(@PathVariable("id")Integer id){
        Map<String,Object> map = new LinkedHashMap<>();
        map.put("type","success");
        map.put("message","获取成功");
        map.put("interview",interviewService.resuemDetail(id));
        return map;
    }

    /*@RequestMapping(value = "/interview/save",method = RequestMethod.POST)
    public Map<String,Object> interviewSave(){

    }*/
}
